<template>
  <div class="liveBottom">
    <div class="bottom_action">
      <!-- 购物车图标 -->
      <div v-if="buycar">
        <img style="width: 35px;" src="@/assets/icons/BuyCar.png" alt="">
        <div class="buycar">
          <div>购物车</div>
        </div>
      </div>
      <div class="input">
        <!-- 功能菜单 -->
        <div class="input-icon" @click="clickMenu" v-if="isMoreAction">
          <img src="@/assets/icons/menu.svg" alt="">
        </div>
        <!-- 输入框 -->
        <div class="input-text">
          <input type="text" v-model="inputValue" :placeholder="silenceInfo" @keyup.enter="sendInfo" :disabled="silence"
            :class="silence ? 'inputDisabled' : ''">
        </div>
        <!-- 发送按钮 -->
        <van-button plain round hairline type="primary" @click="sendInfo" :disabled="silence">发送</van-button>
      </div>
      <div class="like">
        <div class="likeNum">
          <div class="likeNumText">{{ likeNum / 1000 > 0.1 ? likeNum / 1000 + '万' : likeNum / 100 + '千' }}</div>
        </div>
        <img src="@/assets/icons/like.svg" alt="" @click="clickLike">
        <canvas id="thumsCanvas" width="200" height="400" class="canvasBox"></canvas>
      </div>
    </div>

    <DynamicScroller :items="messageList" class="liveMsg" :buffer="100" :min-item-size="10" keyField="id" id="liveMsg"
      @scroll="scrollDome">
      <template #before>
        <div style=" color: #f9b611;width: 80%; ">官方倡导绿色直播，对直播内容进行24小时在线巡查，一切赌毒内容将会封停账号。</div>
      </template>
      <template v-slot="{ item, index, active }">
        <DynamicScrollerItem :item="item" :active="active" :size-dependencies="[item.msg]" :data-index="index">
          <div style="padding: 5px 0;">
            <div class="liveMsgItem">
              <div class="liveMsgItemAvatar">
                <van-image round width="22" height="20" :src="item.userAvatarPreview" fit="cover" />
              </div>
              <div class="liveMsgItemContent">
                <span style="color: #f9b611;">{{ isHideName ? hideNickname(item.nickName) : item.nickName }}</span>
                {{ isHideContent ? hideContact(item.commentContent) : item.commentContent }}
              </div>
            </div>
          </div>
        </DynamicScrollerItem>
      </template>
    </DynamicScroller>

    <!-- 商品弹窗 -->
    <Transition name="slide-fade">
      <div class="goodsCard" v-if="goodsCard"></div>
    </Transition>

    <!-- 直播左侧消息提醒: 进入消息、下单消息-->
    <Transition name="slide-fade">
      <div class="message_dialog" v-if="messageDialog"></div>
    </Transition>

    <!-- <div class="seeLastNews" v-if="!isShowLastNews" @click="isShowLastNews = true">查看最新消息</div> -->

    <!-- 功能按钮弹窗 -->
    <van-action-sheet v-model:show="menuShow" title="功能">
      <GridCard class="profile-action-card" :columnNum="3" :items="ActionCard"></GridCard>
    </van-action-sheet>
  </div>
</template>

<script setup>
import { Toast } from 'vant';
import { DynamicScroller, DynamicScrollerItem } from 'vue-virtual-scroller'
import { addLiveCommentApi } from '@/api/live/index'
// #region 评论模块


// #region 评论引擎
// 测试使用
const AppId = '4a1ba4a6fc69';
const AppKey = '3865895a5055556e9b8fd72ca1ccf456';
const AppSign = 'H4sIAAAAAAAE/wCQAG//zguHB+lYCilkv7diSkk4Gr1c9JQNAmQPk2XZ1Udf/lj0CzfqMW1bso/bCjKzlZSlFrqz38aMkoQAvwpE3ZWO0lex7c+SF2lHOSYZjYwyuNwEyxbx48EAE2Luhh8wky0dLhVcQb3QB/iIwnh/u/mVnjKVrpKnhe8wwCU0zFOiPA4/DpLIgjds8+JvyWc14GrsAAAA//8BAAD//zGZi4CQAAAA';
import { useRoute } from 'vue-router';
const route = useRoute()
const liveId = ref(route.query.liveId) // 直播ID
// 引入阿里直播互动消息SDK
const { ImEngine, ImLogLevel } = window.AliVCInteraction;
// 获取引擎单例
const engine = ImEngine.createEngine();

let groupManager;
let messageManager;
let joinedGroupId;
// 计算输入内容的哈希值
const sha256 = async (message) => {
  // Convert the message string to an ArrayBuffer
  const encoder = new TextEncoder();
  const data = encoder.encode(message);
  // crypto.subtle 这个方法需要在https环境下运行
  // Calculate the hash using the subtle crypto API
  const result = await crypto.subtle.digest('SHA-256', data).then((buffer) => {
    // Convert the ArrayBuffer to a hexadecimal string
    let hash = Array.prototype.map.call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2)).join('');
    return hash;
  });

  return result;
};
// 获取登录认证信息
const getLoginAuth = async (userId, role) => {
  const nonce = 'AK_4';

  const timestamp = Math.floor(Date.now() / 1000) + 3600 * 3;

  const pendingShaStr = `${AppId}${AppKey}${userId}${nonce}${timestamp}${role}`;
  const appToken = await sha256(pendingShaStr);

  return {
    nonce,
    timestamp,
    token: appToken,
    role,
  };
};
// 展示消息
function showMessage(text) {
  console.log('消息事件', text);
}
// 监听引擎事件
function listenEngineEvents() {
  // 处理回调事件  AliVCIMEngineListenerProtocol
  engine.on("connecting", () => {
    console.log("连接中");
  });

  engine.on("connectfailed", (err) => {
    console.log(`连接失败 ${err.message}`);
  });

  engine.on("connectsuccess", () => {
    console.log("引擎连接成功");
  });

  engine.on("disconnect", (code) => {
    console.log(`断开连接: ${code}`);
  });

  engine.on("tokenexpired", async (cb) => {
    console.log("token失效");
    // 这里需要更新为获取新的登录信息的代码
    // const auth = await getLoginAuth(userId, role);
    // cb(null, auth);
  });
}

// 监听群组事件
function listenGroupEvents() {
  if (!groupManager) {
    return;
  }
  // 在适当的时机（例如进入房间后，且完成登录后）添加群组操作事件监听器
  groupManager.on('exit', (groupId, reason) => {
    // 退出群组
    showMessage(`group ${groupId} close, reason: ${reason}`);
  })
  groupManager.on('memberchange', (groupId, memberCount, joinUsers, leaveUsers) => {
    // 有人进入或离开群组
    showMessage(`group ${groupId} member change, memberCount: ${memberCount}, joinUsers: ${joinUsers.map(u => u.userId).join(',')}, leaveUsers: ${leaveUsers.map(u => u.userId).join('')}`);
  })
  groupManager.on('mutechange', (groupId, status) => {
    // 群组的禁言状态发生了变化
    showMessage(`group ${groupId} mute change`);
  })
  groupManager.on('infochange', (groupId, info) => {
    // 有人离开了群组
    showMessage(`group ${groupId} info change`);
  })
}

// 登录
async function login(userId) {
  // 先初始化，注意别忘了加 await
  await engine.init({
    deviceId: "xxxx",    // 设备ID，可选传入
    appId: AppId,     // 开通应用后可以在控制台上拷贝
    appSign: AppSign, // 开通应用后可以在控制台上拷贝
    logLevel: ImLogLevel.ERROR,  // 日志级别，调试时使用 ImLogLevel.DBUG
  });
  // 初始化成功，监听事件
  listenEngineEvents();

  const role = 'admin'; // 是否为admin角色，如果不需要可以设置为空
  // 获取登录信息
  const authData = await getLoginAuth(userId, role);
  // 初始化成功再登录，注意别忘了加 await
  await engine.login({
    user: {
      userId,              // 当前app登录的用户id
      userExtension: '{}', // 用户扩展信息，可以是头像、昵称等封装为json字符串
    },
    userAuth: {
      timestamp: authData.timestamp,  // 服务端返回timestamp值
      nonce: authData.nonce,          // 服务端返回nonce值
      role: authData.role,            // 是否为admin角色，如果不需要可以设置为空
      token: authData.token,          // 服务端返回token值
    },
  });

  // 必须确保已经初始化，否则会返回空值
  groupManager = engine.getGroupManager();
  messageManager = engine.getMessageManager();
}

// 退出登录
async function logout() {
  await engine.logout();
  engine.unInit();
  groupManager = undefined;
  messageManager = undefined;
}
// 加入群组
async function joinGroup(groupId) {
  if (!groupManager) {
    return;
  }
  await groupManager.joinGroup(groupId);
  joinedGroupId = groupId;
  listenGroupEvents();
  listenMessageEvents();
}
// 离开群组
async function leaveGroup() {
  if (!groupManager || !joinedGroupId) {
    return;
  }
  await groupManager.leaveGroup(joinedGroupId);
  groupManager.removeAllListeners();
  messageManager.removeAllListeners();
}

// 挂载时直接进入群组
onMounted(async () => {
  try {
    await login('lgy');
    console.log('登录成功');

    await joinGroup(liveId.value);
    console.log('加入群组成功');
  } catch (err) {
    console.log('一键登录+加入群组', err.code, err.msg);
  }
})
// 离开页面时退出群组
onUnmounted(async () => {
  // 先离开群组，无论成功与否，都继续执行 logout
  try {
    await leaveGroup();
  } catch (error) {
    console.log(error);
  }
  try {
    await logout();
  } catch (error) {
    console.log(error);
  }
})
// #endregion

//#region 评论功能

const inputValue = ref('')      // 输入框内容
const messageList = ref([])     // 评论列表
const isShowLastNews = ref(true)// 是否符合触底条件
const silence = ref(false)      // 是否禁言
const silenceInfo = ref('说点什么~')     // 禁言提示
// 发送消息
function sendInfo() {
  emitter.emit('isHeatMitt', false)
  if (silence.value) {
    Toast('你已被禁言!'); // 禁言状态
    return
  }
  // 消息引擎 群组 消息内容 有一个为空就不发送
  if (!messageManager || !joinedGroupId || !inputValue.value) return;
  // 消息引擎发送消息
  addLiveCommentApi({
    commentContent: inputValue.value,
    liveId: liveId.value,
    userType: "0"
  }).then((res) => {
    if (res.code == 200) {
      isShowLastNews.value = true // 使评论区滚动到底部
      showTheLastNews()
    }
  })
  inputValue.value = '' // 清空输入框
}
// 监听消息事件
function listenMessageEvents() {
  if (!messageManager) {
    return;
  }
  // 收到群聊消息
  messageManager.on("recvgroupmessage", (msgData, groupId) => {
    console.log('监听消息事件', msgData);
    let msgInfo
    try {
      msgInfo = JSON.parse(msgData.data) // 后端处理过的消息
    } catch (error) {
      msgInfo = msgData.data
    }
    if (msgData.type === 10001 && msgInfo.commentState == '1') { // 推送消息
      messageList.value.push(msgInfo)
      showTheLastNews()
    } else if (msgData.type === 10002 && msgInfo.commentState == '2') { // 过滤消息
      // 过滤掉审核不通过的消息
      messageList.value = messageList.value.filter((item) => {
        return !msgInfo.ids.includes(item.id)
      })
      showTheLastNews()
    } else if (msgData.type === 10003) { // 用户禁言
      console.log('禁言用户ID', msgInfo.userId);
      silence.value = true
      silenceInfo.value = '你已被禁言!'
      Toast('你已被禁言!');
    } else if (msgData.type === 10004) { // 解除禁言
      console.log('解除禁言ID', msgInfo.userId);
      silence.value = false
      silenceInfo.value = '说点什么~'
      Toast('已解除禁言!');
    } else if (msgData.type === 10005) { // 删除消息
      messageList.value = messageList.value.filter((item) => {
        return !msgInfo.ids.includes(item.id)
      })
    } else if (msgData.type === 20001) { // 开始推流
      emit('getLiveStream')
    } else if (msgData.type === 20002) { //直播流
      if (msgInfo.liveStatus == '2') {
        //推流
        emit('getLiveStream')
        console.log('恢复推流');

      } else if (msgInfo.liveStatus == '5') {
        //暂停
        emit('handleLivePauses')
        console.log('暂停推流');
      }
    } else if (msgData.type === 20003) { // 直播结束
      emit('handleLiveEnd')
      console.log('直播结束');
    } else if (msgData.type === 30001) { //点赞 没有额外逻辑的处理
    } else if (msgData.type === 30002) { //卡片推送

    } else if (msgData.type === 30003) { // 推送点赞总数
      likeNum.value = msgInfo.likeTimes
      thumsUpAni.start()
      setTimeout(() => {
        thumsUpAni.start()
      }, Math.floor(Math.random() * (3000 - 1000 + 1)) + 1000);
    }
  });
}
// 显示最新消息
function showTheLastNews() {
  if (isShowLastNews.value) {
    nextTick(() => {
      const liveMsgDom = document.querySelector('#liveMsg')
      liveMsgDom.scrollTop = liveMsgDom.scrollHeight
    })
  }
}
// 手动滚动时,不再显示最新消息
function scrollDome() {
  const liveMsgDom = document.querySelector('#liveMsg')
  const scrollBottom = liveMsgDom.scrollHeight - liveMsgDom.scrollTop - liveMsgDom.clientHeight
  if (scrollBottom > 20) {
    isShowLastNews.value = false
  } else {
    isShowLastNews.value = true
  }
}

// 禁言状态
// function getLiveIsBan() {
//   getLiveIsBanApi(liveRoomId).then(res => {
//     if (res.code == 200) {
//       isBan.value = res.data
//       console.log('禁言状态', res);
//     }
//   })
// }

//#endregion
// #endregion


// #region 点赞
import { ThumbsUpAni } from './canvas'
let thumsUpAni
const likeNum = ref(0) // 点赞数量
const isLike = ref(true) // 是否开启点赞
onMounted(() => {
  thumsUpAni = new ThumbsUpAni()
})
let i = 0
function clickLike() {
  if (!isLike.value) {
    Toast('点赞已关闭');
    return
  }
  thumsUpAni.start()
  i++
  if (!messageManager) {
    return;
  }
  if (i >= 10) {
    messageManager.sendGroupMessage({
      groupId: liveId.value,     // 群组id
      data: '',             // 消息内容
      type: 30001,          // 自定义消息类型，需大于10000
    })
    i = 0
  }
}

// #endregion

//#region 功能按钮
const menuShow = ref(false)
function clickMenu() {
  console.log('点击功能按钮');
  menuShow.value = true
}

import { defineEmits } from 'vue'

const emit = defineEmits()

const ActionCard = reactive({
  Order: {
    text: '我的订单',
    svg: 'Order',
    to: '/my/orderList?status=0'
  },
  Withdrawal: {
    text: '清屏',
    svg: 'Withdrawal',
    func: () => {
      emit('hideUI') // 清屏
      menuShow.value = false //关闭弹层
    }
  },
  Friend: {
    text: '我的优惠券',
    svg: 'Friend',
  },
  Profit: {
    text: '我的邀请',
    svg: 'Profit',
  }
})
//#endregion

//#region 直播设置
import { getLiveLookSetPageInteractionApi, getLiveLookSetPageInfoApi } from '@/api/live/index'
const messageDialog = ref(true) // 消息弹窗,进入消息和购买消息
const goodsCard = ref(true)    // 商品弹窗
// 互动设置
const LiveLookSetPageInteractionForm = ref({})
function getLiveLookSetPageInteraction() {
  getLiveLookSetPageInteractionApi(liveId.value).then((res) => {
    console.log('直播设置信息', res.data);

    LiveLookSetPageInteractionForm.value = res.data
    // 禁止发弹幕 0关闭1开启
    if (LiveLookSetPageInteractionForm.value.barrage == '0') {
      Toast('全员禁言');
      silence.value = true
      silenceInfo.value = '已开启全员禁言'
    }
    // 点赞
    LiveLookSetPageInteractionForm.value.agree == '0' ? isLike.value = false : isLike.value = true
  })
}
// 观看页设置
import emitter from '@/utils/mitt'

const isHideName = ref(false)    // 隐藏昵称
const isHideContent = ref(false) // 隐藏联系方式
const isMoreAction = ref(false)

function getLiveLookSetPageInfo() {
  getLiveLookSetPageInfoApi(liveId.value).then((res) => {
    console.log('观看页设置', res.data);
    // 如果是管理员则都可以显示
    // 隐藏昵称
    res.data.hideNickname == '1' ? isHideName.value = true : isHideName.value = false
    // 隐藏联系方式
    res.data.hideContact == '1' ? isHideContent.value = true : isHideContent.value = false
    // 实时人数和热度 emitter触发liveTop.vue中的方法
    if (res.data.dataIndex == '1') {
      if (res.data.dataIndexType.includes('0')) {
        nextTick(() => {
          emitter.emit('isHeatMitt', true)
        })
      }
      if (res.data.dataIndexType.includes('1')) {
        nextTick(() => {
          emitter.emit('isOnlineMitt', true)
        })
      }
    }
    // 更多操作
    res.data.moreAction == '1' ? isMoreAction.value = true : isMoreAction.value = false
  })
}
// 隐藏昵称
function hideNickname(name) {
  return name.charAt(0) + '*'.repeat(name.length - 1)
}
// 隐藏联系方式
function hideContact(str) {
  if (!str) return str;
  const regex = /\d{6,}/g;
  return str.replace(regex, match => match.slice(0, 3) + '*'.repeat(match.length - 3));
}

onMounted(() => {
  getLiveLookSetPageInteraction()
  getLiveLookSetPageInfo()
})
//#endregion

//#region 购物车
const buycar = ref(false)
//#endregion

</script>

<style lang="scss" scoped>
.liveBottom {
  position: absolute;
  bottom: 0;
  z-index: 99;
  height: 40vh;
  display: flex;
  flex-direction: column-reverse; // 倒序
  width: 100%;
  font-size: 14px;

  // 无限滚动
  .liveMsg {
    overflow-y: auto;
    margin: 0 10px;
    padding-top: 40px;
    color: #fff;
    font-size: 16px;
    // 顶部完全透明到20%完全不透明
    -webkit-mask-image: linear-gradient(to bottom, transparent 0%, #fff 20%);
    height: 100%;

    .liveMsgItem {
      max-width: 80%;
      display: flex;
      background-color: rgba(0, 0, 0, 0.4);
      padding: 5px;
      border-radius: 15px;
      width: fit-content; // 宽度根据内容自适应
      word-wrap: break-word;
      word-break: break-all;

      .liveMsgItemAvatar {
        margin: 1px 5px 0 1px;
        display: flex;
        align-items: flex-start;
      }

      .liveMsgItemContent {
        margin-right: 5px;
        margin-left: 5px;
        display: -webkit-box;
        -webkit-line-clamp: v-bind('LiveLookSetPageInteractionForm.barrageRows');
        /* Limit to 3 lines */
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        /* Add ellipsis */
        color: v-bind('LiveLookSetPageInteractionForm.barrageColor')
      }
    }
  }

  .seeLastNews {
    position: absolute;
    color: #fff;
    bottom: 50px;
    left: 20px;
    z-index: 100;
    padding: 5px 20px 15px 10px;
    border-radius: 5px;
    background: url('@/assets/icons/msg.png') 100% 100%;
  }

  .bottom_action {
    display: flex;
    align-items: center;
    margin: 5px;

    .input {
      flex: 1;
      padding: 0px;
      margin-right: 5px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: rgba(0, 0, 0, 0.4);
      border-radius: 100px;
      color: #fff;

      .input-text {
        padding-left: 7px;
        flex: 1;
        font-size: 15px;

        .inputDisabled {
          &::placeholder {
            color: #c6c5c5;
          }
        }

        input {
          border: none;
          background-color: transparent;
          width: 100%;

          &::placeholder {
            color: #fff;
          }
        }
      }

      .input-icon {
        display: flex;
        align-items: center;
        border-right: 3px solid #c6c5c5;

        img {
          width: 20px;
          height: 16px;
          margin: 0 10px 0 15px;
        }
      }
    }

    .like {
      display: flex;
      background-color: rgba(0, 0, 0, 0.4);
      border-radius: 100px;
      padding: 5px;

      .likeNum {
        position: absolute;
        bottom: 45px;
        right: 0;
        margin-right: 5px;

        .likeNumText {
          display: flex;
          justify-content: center;
          background-color: red;
          color: #fff;
          border-radius: 100px;
          padding: 5px 5px;
          white-space: nowrap;
        }
      }

      img {
        width: 35px;
        height: 35px;
      }

      .canvasBox {
        width: 100px;
        height: 200px;
        position: absolute;
        bottom: 55px;
        right: -15px;
        background-color: transparent;
      }
    }

  }

}

:deep(.van-button) {
  height: 35px;
  margin: 5px 7px;
}

:deep(.vue-recycle-scroller__item-wrapper) {
  overflow: visible;
}
</style>